<template>
    <div>
        <!-- 绑定到实际的数据数组tableData，而不是函数 -->
        <el-table :data="tableData" style="width: 100%">
            <el-table-column label="ID" prop="id" />
            <el-table-column label="设备名称" prop="device_name" />
            <el-table-column label="设备地址" prop="location" />
            <el-table-column label="设备制造商" prop="manufacturer" />
            <el-table-column label="型号" prop="model" />
            <el-table-column label="安装日期" prop="install_date" />
            <el-table-column label="最后维护日期" prop="last_maintain_date" />
            <el-table-column label="设备IP" prop="ip_address" />
            <el-table-column label="设备状态" prop="status" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">
                        修改
                    </el-button>
                    <el-button size="small" type="danger" @click="open(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-button type="primary" @click="handleAdd">添加</el-button>


        <el-drawer v-model="dialog" title="设备信息编辑" direction="rtl" class="demo-drawer">
            <div class="demo-drawer__content">
                <el-form :model="form" label-position="left">
                    <el-form-item label="设备名称" :label-width="formLabelWidth">
                        <el-input v-model="form.device_name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="设备地址" :label-width="formLabelWidth">
                        <el-input v-model="form.location" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="设备制造商" :label-width="formLabelWidth">
                        <el-input v-model="form.manufacturer" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="型号" :label-width="formLabelWidth">
                        <el-input v-model="form.model" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="安装日期" :label-width="formLabelWidth">
                        <el-date-picker v-model="form.install_date" type="date" placeholder="选择安装日期" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="最后维护日期" :label-width="formLabelWidth">
                        <el-date-picker v-model="form.last_maintain_date" type="date" placeholder="选择最后维护日期"
                            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="IP地址" :label-width="formLabelWidth">
                        <el-input v-model="form.ip_address" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="设备状态" :label-width="formLabelWidth">
                        <el-select v-model="form.status" placeholder="请选择设备状态">
                            <el-option label="正常" value="正常" />
                            <el-option label="异常" value="异常" />
                            <el-option label="维护中" value="维护中" />
                            <el-option label="已停用" value="已停用" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <div class="demo-drawer__footer">
                    <el-button @click="cancelForm">取消</el-button>
                    <el-button type="primary" :loading="loading" @click="onClick">
                        {{ loading ? '提交中 ...' : '提交' }}
                    </el-button>
                </div>
            </div>
        </el-drawer>

    </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { el } from 'element-plus/es/locales.mjs'

// 使用reactive创建响应式数组
const tableData = reactive([])

// 抽屉
const dialog = ref(false)
const loading = ref(false)
const formLabelWidth = '120px'
const form = reactive({
    id: 0,
    device_name: '',
    manufacturer: '',
    model: '',
    install_date: '',
    last_maintain_date: '',
    location: '',
    ip_address: '',
    status: ''
});


// 定义对话框类型
let dialogType = ref('')

// 定义获取数据的异步函数
const getData = async () => {
    try {
        const res = await axios.get('http://localhost:8081/s2exam/iotDevices?opr=all')
        console.log("res", res);

        // 清空现有数据并添加新数据（避免重复）
        tableData.length = 0
        tableData.push(...res.data.data)
    } catch (error) {
        console.error('获取数据失败:', error)
    }
}

// 修改数据
const handleEdit = (row: any) => {
    // 打开抽屉
    dialog.value = true
    // 将选中行的数据赋值给表单
    Object.assign(form, row)
    dialogType.value = 'edit'
}
const handleAdd = (row: any) => {
    // 打开抽屉
    dialog.value = true
    // 将选中行的数据赋值给表单
    dialogType.value = 'add'
    // 清空表单数据
    Object.keys(form).forEach(key => {
        form[key] = ''
    })
}

// 删除数据
const handleDelete = async (row: any) => {
    try {
        const { data } = await axios.post(`http://localhost:8081/s2exam/iotDevices?opr=delete`, { id: row.id }, { headers: { 'Content-Type': 'application/json' } });
        console.log("data", data);
        // 删除成功后重新获取数据
        if (data.status == 1) {
            ElMessage({
                type: 'success',
                message: '删除成功',
            });
        } else {
            ElMessage({
                type: 'error',
                message: '删除失败',
            });

        }
        getData()
    } catch (error) {
        console.error('删除数据失败:', error)
    }
}

// 取消表单
const cancelForm = () => {
    dialog.value = false

}


const open = (row: any) => {
    ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            handleDelete(row)
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            });
        });
};

// 提交表单
const onClick = async () => {
    loading.value = true
    try {
        // 编辑操作
        let res = null
        if (dialogType.value == 'edit') {
            res = await axios.post('http://localhost:8081/s2exam/iotDevices?opr=update', form, { headers: { 'Content-Type': 'application/json' } })
        } else if (dialogType.value == 'add') {
            res = await axios.post('http://localhost:8081/s2exam/iotDevices?opr=add', form, { headers: { 'Content-Type': 'application/json' } })
        }

        console.log("res", res);

        if (res.data.status == 1) {
            ElMessage.success(res.data.message)
        } else {
            ElMessage.success(res.data.message)
        }

        dialog.value = false
        getData()
    } catch (error) {
        console.error('提交数据失败:', error)
    } finally {
        loading.value = false
    }
}

// 在组件挂载后调用获取数据的函数
onMounted(() => {
    getData()
})
</script>
